package org.bird.reference;

/**
 * 软引用:非必须引用,内存溢出之前进行回收
 * @VM args : -Xms5M -Xmx5M -XX:+PrintGCDetails -XX:+HeapDumpOnOutOfMemoryError
 * @author liangjf
 *
 */
public class SoftReference {

	public static void main(String[] args) throws InterruptedException {
		SoftReference sf = new SoftReference();
		Thread.sleep(50000);
		@SuppressWarnings("unused")
		Browser rev;
		System.out.println("添加当前浏览页prev内存");
		Browser prev = sf.new Browser(new String[350000]); // 获取页面进行浏览
		java.lang.ref.SoftReference<Browser> sr = new java.lang.ref.SoftReference<Browser>(prev); // 浏览完毕后置为软引用
	    System.gc();
		Thread.sleep(50000);

		if (sr.get() != null) {//@VM args : -Xms5M -Xmx5M
			System.out.println("添加当前浏览页prev内存未被回收");
			rev = (Browser) sr.get(); // 还没有被回收器回收，直接获取
		} else {//@VM args : -Xms4M -Xmx4M
			System.out.println("添加当前浏览页prev内存已被回收");
			prev = sf.new Browser(new String[100000]); // 由于内存吃紧，所以对软引用的对象回收了
			sr = new java.lang.ref.SoftReference<Browser>(prev); // 重新构建
		}
		Thread.sleep(50000);
	}

	class Browser {

		private String[] objects;
		
		public Browser(String[] objects) {
			this.objects = objects;
		}

		public String[] getObjects() {
			return objects;
		}

		public void setObjects(String[] objects) {
			this.objects = objects;
		}
	}
}
